package nancal.mp.mvc.dev

import io.swagger.annotations.*
import nancal.mp.db.mongo.*
import nancal.mp.db.mongo.entity.*
import nancal.mp.db.mongo.entity.dev.*
import nbcp.base.annotation.*
import nbcp.base.annotation.mvc.*
import nbcp.base.comm.*
import nbcp.base.db.CodeName
import nbcp.base.db.IdName
import nbcp.base.db.annotation.Cn
import nbcp.base.extend.*
import nbcp.mvc.sys.*
import nbcp.myoql.db.*
import nbcp.myoql.db.mongo.*
import nbcp.web.*

import org.springframework.data.mongodb.core.query.*
import org.springframework.web.bind.annotation.*
import java.time.*
import javax.servlet.http.*

/**
 * Created by CodeGenerator at 2024-04-06 18:53:39
 */
@Api(description = "模型树", tags = arrayOf("ModelTreeType"))
@RestController
@RequestMapping("/dev/data-model-tree")
class ModelTreeTypeAutoController {


    class ModelTreeTypeWithChildren {
        var id: String = ""
        var productLine: CodeName = CodeName()

        @Cn("应用")
        var app: String = ""
        var name: String = ""
        var cnName: String = ""
        var tableView: TableViewTypeEnum? = null

        /**
         * 逻辑父
         */
        var logicParent: IdName = IdName()
        var logicChildren: MutableList<ModelTreeTypeWithChildren> = mutableListOf()
    }

    @ApiOperation("列表")
    @PostMapping("/list")
    fun list(
        id: String, //当列表列新一条后，刷新时使用
        ids: List<String>,
        productLineCode: String,
        app: String,
        @org.springframework.web.bind.annotation.RequestBody query: PagerModel<Any?>
    ): List<ModelTreeTypeWithChildren> {

        var dbList = mor.dev.dataModel.query()
            .apply {
                if (id.HasValue) {
                    this.where { it.id mongoEquals id }
                }

                if (ids.HasValue) {
                    this.where { it.id mongoIn ids }
                }

                if (productLineCode.HasValue) {
                    this.where { it.productLine.code mongoEquals productLineCode }
                }

                if (app.HasValue) {
                    this.where { it.app mongoEquals app }
                }
            }
            .select { it.name }
            .select { it.cnName }
            .select { it.logicParent }
            .withPager(query)
            .toList(ModelTreeTypeWithChildren::class.java)


        var ret = mutableListOf<ModelTreeTypeWithChildren>();
        //填充 children

        fillChildren(ret, dbList, if (id.HasValue) dbList.first().logicParent.id else "");
        return ret;
    }

    @PostMapping("/add-model/{typeId}/{modelId}")
    fun addModel(
        @Require typeId: String,
        @org.springframework.web.bind.annotation.RequestBody modelId: String
    ): List<ModelTreeTypeWithChildren> {
        if (typeId == modelId) {
            throw RuntimeException("非法!")
        }

        var allIds = listOf(typeId, modelId);
        var models = mor.dev.dataModel.query()
            .where { it.id mongoIn allIds }
            .toList();

        if (models.size != 2) {
            throw RuntimeException("找不到模型")
        }

        var typeModel = models.first { it.id == typeId }
        var model = models.first { it.id == modelId }
        if (model.logicParent.id == typeModel.id) {
            return listOf()
        }


        mor.dev.dataModel.updateById(modelId)
            .set { it.logicParent to IdName(typeModel.id, typeModel.name) }
            .exec()


        return list("", allIds, "", "", PagerModel());
    }


    @PostMapping("/cut-model/{modelId}")
    fun removeModel(
        @org.springframework.web.bind.annotation.RequestBody modelId: String
    ): List<ModelTreeTypeWithChildren> {
        mor.dev.dataModel.updateById(modelId)
            .set { it.logicParent to IdName() }
            .exec()


        return list(modelId, listOf(), "", "", PagerModel());
    }

//    @PostMapping("/set-models/{typeId}")
//    fun setModels(
//        @Require typeId: String,
//        @org.springframework.web.bind.annotation.RequestBody modelIds: List<String>
//    ): JsonResult {
//
//        var models = mor.dev.dataModel.query()
//            .where { it.id mongoIn modelIds }
//            .toList()
//
//        mor.dev.modelTreeType.updateById(typeId)
//            .set { it.models to models.map { IdName(it.id, it.name) } }
//            .exec()
//
//        return JsonResult();
//    }


    private fun fillChildren(
        ret: MutableList<ModelTreeTypeWithChildren>,
        dbList: MutableList<ModelTreeTypeWithChildren>,
        pid: String
    ) {
        ret.addAll(dbList.filter { it.logicParent.id == pid }
            .map { it.ConvertType(ModelTreeTypeWithChildren::class.java) as ModelTreeTypeWithChildren }
        )


        ret.forEach {
            fillChildren(it.logicChildren, dbList, it.id);
        }
    }

    @ApiOperation("详情")
    @PostMapping("/detail/{id}")
    fun detail(
        @Require id: String,
        request: HttpServletRequest
    ): ApiResult<ModelTreeTypeWithChildren> {
        var list = list(id, listOf(), "", "", PagerModel());
        if (list.size == 0) {
            return ApiResult.error("找不到数据");
        }
        return ApiResult.of(list.first())
    }
}